import { ShElement } from './ShElement'


/**
 * 垂直分割栏，可以水平拖动。拖动结束后，将触发 `shev-splitter-move` 事件。
 * 
 */
export class ShVSplitter extends ShElement {

    constructor() {
        super()
        
        this.$shadow.innerHTML = `
            <style>
                :host {
                    background-color: var(--color-ctrl);                    
                    display: flex;
                    align-items: center;
                    border-left: var(--border-ctrl);
                    border-right: var(--border-ctrl);
                }
                div {
                    width: 3px;
                    height: 100px;
                    border-left: var(--border-ctrl);
                    border-right: var(--border-ctrl);
                    cursor: ew-resize;
                }
            </style>
            <div></div>
        `
        
        const $grabber = this.$shadow.querySelector('div')!
        $grabber.on('pointerdown', this.ondragbegin)
    }

    private ondragbegin = (e: PointerEvent) => {
        const { left, top } = this.locationInViewport()

        // 创建一个透明的遮罩层，维持鼠标形状
        const $screen = document.createElement('div')
        $screen.updateStyle({
            position: 'fixed',
            inset: '0',
            zIndex: '1000',
            backgroundColor: 'transparent',
            cursor: 'ew-resize',
        })
        document.body.append($screen)

        // 创建随鼠标移动的拖拽条
        const $dragger = document.createElement('div')
        $dragger.updateStyle({
            position: 'fixed',
            left: left + 'px',
            top: top + 'px',
            width: this.offsetWidth + 'px',
            height: this.offsetHeight + 'px',
            backgroundColor: 'rgba(0, 0, 0, 0.5)',
            cursor: 'ew-resize',
        })
        $screen.append($dragger)

        const delta = e.clientX - left

        const ondragging = (e: PointerEvent) => { 
            $dragger.style.left = e.clientX - delta + 'px'
            e.preventDefault()
        }
        const ondragend = () => {
            this.dispatchEvent(new CustomEvent('shev-splitter-move', { detail: $dragger.offsetLeft - left }))
            $screen.remove()
            $dragger.remove()
            $screen.removeEventListener('pointermove', ondragging)
            $screen.removeEventListener('pointerup', ondragend)
        }
        $screen.addEventListener('pointermove', ondragging)
        $screen.addEventListener('pointerup', ondragend)
    }
}
customElements.define('sh-v-splitter', ShVSplitter)